import axios from 'axios';
import { getToken } from "@/utils/auth";

/**
 * 上传单个文件
 * @param {File} file - 要上传的文件
 * @param config
 * @returns {Promise<Object>} - 上传结果
 */
export async function uploadSingleFile(file) {
    if (!file) throw new Error('请选择一个文件');

    const formData = new FormData();
    formData.append('file', file);

    const token = getToken() // 获取 token
    const uploadUrl = `${import.meta.env.VITE_APP_BASE_API}/common/upload`; // 根据环境变量获取上传 URL

    try {
        const response = await axios.post(uploadUrl, formData, {
            headers: {
                'Content-Type': 'multipart/form-data',
                'Authorization': `Bearer ${token}` // 添加 token 到请求头
            },
        });
        return response.data;
    } catch (error) {
        console.error('上传失败:', error);
        throw error;
    }
}

/**
 * 上传多个文件
 * @param {File[]} files - 要上传的文件数组
 * @returns {Promise<Object>} - 上传结果
 */
export async function uploadMultipleFiles(files) {
    if (!files || files.length === 0) throw new Error('请选择文件');

    const formData = new FormData();
    files.forEach((file) => formData.append('files', file));

    const token = getToken(); // 获取 token
    const uploadUrl = `${import.meta.env.VITE_APP_BASE_API}/common/uploads`; // 根据环境变量获取上传 URL

    try {
        const response = await axios.post(uploadUrl, formData, {
            headers: {
                'Content-Type': 'multipart/form-data',
                'Authorization': `Bearer ${token}` // 添加 token 到请求头
            },
        });
        return response.data;
    } catch (error) {
        console.error('上传失败:', error);
        throw error;
    }
}

/**
 * 下载文件
 * @param {string} fileName - 文件名
 */
export async function downloadFile(fileName) {
    if (!fileName) throw new Error('请输入文件名');

    const token = getToken(); // 获取 token
    const downloadUrl = `${import.meta.env.VITE_APP_BASE_API}/common/download?fileName=${fileName}`; // 根据环境变量获取下载 URL

    try {
        const response = await axios.get(downloadUrl, {
            responseType: 'blob',
            headers: {
                'Authorization': `Bearer ${token}` // 添加 token 到请求头
            },
        });

        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', fileName);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    } catch (error) {
        console.error('下载失败:', error);
        throw error;
    }
}
